﻿@model NewsItemListModel
@using Telerik.Web.Mvc.UI

@{
    var gridPageSize = EngineContext.Current.Resolve<SmartStore.Core.Domain.Common.AdminAreaSettings>().GridPageSize;

    ViewBag.Title = T("Admin.ContentManagement.News.NewsItems").Text;
}

<div class="section-header">
    <div class="title">
        <i class="fa fa-rss"></i>
        @T("Admin.ContentManagement.News.NewsItems")
    </div>
    <div class="options">
		@{ Html.RenderWidget("admin_button_toolbar_before"); }

		<a href="@Url.Action("Create")" class="btn btn-primary">
			<i class="fa fa-plus"></i>
			<span>@T("Admin.Common.AddNew")</span>
		</a>

		<button type="submit" id="delete-selected" name="delete-selected" value="delete_selected" class="btn btn-danger">
			<i class="far fa-trash-alt"></i>
			<span>@T("Admin.Common.Delete.Selected")</span>
		</button>

		@{ Html.RenderWidget("admin_button_toolbar_after"); }
    </div>
</div>

@if (Model.AvailableStores.Count > 1)
{
	<div class="row mt-3 grid-filter">
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchStoreId)
			@Html.DropDownListFor(model => model.SearchStoreId, Model.AvailableStores, T("Admin.Common.All"), new { @class = "form-control" })
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabel(string.Empty, string.Empty)
			<button type="submit" id="btnSearch" value="btnSearch" class="btn btn-secondary btn-block">
				<span>@T("Admin.Common.ApplyFilter")</span>
			</button>
		</div>
	</div>
}

<div>
	@(Html.Telerik().Grid<NewsItemModel>()
			.Name("newsitem-grid")
			.Columns(columns =>
			{
			columns.Bound(x => x.Id)
				.ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
				.Title("<input id='mastercheckbox' type='checkbox'/>")
				.HtmlAttributes(new { style = "text-align:center" })
				.HeaderHtmlAttributes(new { style = "text-align:center" });
			columns.Bound(x => x.Title)
				.Width(450)
				.Template(x => Html.ActionLink(x.Title, "Edit", new { id = x.Id }))
				.ClientTemplate("<a href=\"Edit/<#= Id #>\"><#= Title #></a>");
			columns.Bound(x => x.Published)
				.Template(item => @Html.SymbolForBool(item.Published))
				.ClientTemplate(@Html.SymbolForBool("Published"))
				.Centered();
			columns.Bound(x => x.LanguageName);
			columns.Bound(x => x.Comments)
				.Template(
				@<div>
					@Html.ActionLink(T("Admin.ContentManagement.News.NewsItems.Fields.Comments").Text + " - " + @item.Comments, "Comments", new { filterByNewsItemId = item.Id })
				</div>
					)
					.ClientTemplate("<div><a href=\"Comments?filterByNewsItemId=<#= Id #>\">" + T("Admin.ContentManagement.News.NewsItems.Fields.Comments").Text + " - <#= Comments #>" + "</a></div>");
				columns.Bound(x => x.StartDate);
				columns.Bound(x => x.EndDate);
				columns.Bound(x => x.LimitedToStores)
					.Template(item => @Html.SymbolForBool(item.LimitedToStores))
					.ClientTemplate(@Html.SymbolForBool("LimitedToStores"))
					.Hidden(Model.AvailableStores.Count <= 1)
					.Centered();
				columns.Bound(x => x.CreatedOn);
			})
			.Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
			.DataBinding(dataBinding => dataBinding.Ajax().Select("List", "News"))
			.ClientEvents(events => events.OnDataBinding("onDataBinding").OnDataBound("onDataBound").OnRowDataBound("onRowDataBound"))
			.PreserveGridState()
			.EnableCustomBinding(true))
</div>



<script type="text/javascript">
	var selectedIds = [];

    $(document).ready(function () {
        //search button
        $('#search-newsitem').click(function () {
            //search
            var grid = $('#newsitem-grid').data('tGrid');
            //no paging support in this grid
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
        	//clear selected checkboxes
            $('.checkboxGroups').attr('checked', false).change();
            selectedIds = [];
            return false;
        });

    	//"delete selected" button
        $('#delete-selected').click(function (e) {
        	e.preventDefault();

        	var postData = {
        		selectedIds: selectedIds
        	};

        	$.ajax({
        		cache:false,
        		type: "POST",
        		url: "@(Url.Action("DeleteSelected", "News"))",
        		data: postData,
        		complete: function (data) {
        			//reload grid
        			var grid = $('#newsitem-grid').data('tGrid');
        			grid.currentPage = 1; //new search. Set page size to 1
        			grid.ajaxRequest();
        			//clear selected checkboxes
        			$('.checkboxGroups').attr('checked', false).change();
        			selectedIds = [];
        		},
        		error:function (xhr, ajaxOptions, thrownError){
        			alert(thrownError);
        		},
        		traditional: true
			});
			return false;
        });

    	$('#mastercheckbox').click(function () {
    		$('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
    	});

    	//wire up checkboxes. 
    	$(document).on('change', '#newsitem-grid input[type=checkbox][id!=mastercheckbox]', function (e) {
    		var $check = $(this);
    		if ($check.is(":checked") == true) {
    			var checked = jQuery.inArray($check.val(), selectedIds);
    			if (checked == -1) {
    				//add id to selectedIds.  
    				selectedIds.push($check.val());
    			}
    		}
    		else {
    			var checked = jQuery.inArray($check.val(), selectedIds);
    			if (checked > -1) {
    				//remove id from selectedIds.  
    				selectedIds = $.grep(selectedIds, function (item, index) {
    					return item != $check.val();
    				});
    			}
    		}
    		updateMasterCheckbox();
    	});

    });

    function onDataBinding(e) {
        var searchModel = {
            SearchStoreId: $('#SearchStoreId').val()
        };
        e.data = searchModel;
    }

    function onRowDataBound(e) {
    	if (!e.dataItem.Published) {
    		$(e.row).find('td').wrapInner('<span class="muted" />');
    	}
    }

    function onDataBound(e) {
    	$('#newsitem-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
    		var currentId = $(this).val();
    		var checked = jQuery.inArray(currentId, selectedIds);
    		//set checked based on if current checkbox's value is in selectedIds.  
    		$(this).attr('checked', checked > -1);
    	});

    	updateMasterCheckbox();
    }

    function updateMasterCheckbox() {
    	var numChkBoxes = $('#newsitem-grid input[type=checkbox][id!=mastercheckbox]').length;
    	var numChkBoxesChecked = $('#newsitem-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
    	$('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }
</script>